<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends DocumentRepository implements PasswordUpgraderInterface
{

    public function __construct(
        DocumentManager $dm
    )
    {
        parent::__construct($dm, $dm->getUnitOfWork(),$dm->getClassMetadata(User::class));
//        parent::__construct($registry, User::class);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
        }

        $user->setPassword($newEncodedPassword);
        $this->dm->persist($user);
        $this->dm->flush();
    }

    /**
     * @param $value
     * @return User|null
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findOneByPhone($value): ?User
    {
        return $this->findOneBy(array("phone"=>$value));
    }

    public function findOneByWx($openIdOrUnionId)
    {
        $user =  $this->findOneBy(array("openid"=>"$openIdOrUnionId"));
        if (!$user) {
            $user =  $this->findOneBy(array("unionid"=>"$openIdOrUnionId"));
        }
        return $user;
    }

//    public function dealWithLevel(User $user)
//    {
//        $list = $this->userLevelRepository->findBy(array(),array("sort"=>"ASC"));
//        $lastExpr = 0;
//        foreach ($list as $key => $row) {
//            if ($user->getExpr() > $lastExpr && $user->getExpr() <= $row->getExpr()) {
//                $user->setLevel($row);
//            }
//            if ($user->getExpr() >  $row->getExpr() && $key == count($list) - 1 ) {
//                $user->setLevel($row);
//            }
//        }
//        $this->_em->persist($user);
//        $this->_em->flush();
//    }

}
